﻿/* Write a program that deletes from given text file all odd lines. 
 * The result should be in the same file. */

using System;
using System.IO;
using System.Text;

namespace _9.DeleteOddLines
{
    class DeleteOddLines
    {
        static void Main()
        {
            Console.Write("Path to file: ");
            string path_to_input_file = Console.ReadLine();
            string line; 
            StringBuilder newlines = new StringBuilder();
            int counter = 0;
            try
            {
                StreamReader SR = new StreamReader(@path_to_input_file);
                line = SR.ReadLine();
                using (SR)
                {
                    while (line != null)
                    {
                        if (counter % 2 != 0) newlines.AppendLine(line);
                        else newlines.AppendLine(); //leave an empty line if the counter is on odd position
                        line = SR.ReadLine();
                        ++counter;
                    }
                }
            }
            catch (FileNotFoundException fn)
            {
                throw new FileNotFoundException("File not found, " + fn.Message);
            }
            catch (OverflowException oe)
            {
                throw new OverflowException("Stack overflow, may be the file is too big?, " + oe.Message);
            }
            catch (IOException ioe)
            {
                throw new IOException("Error: the input file could not be read, " + ioe.Message);
            }
            //write to file
            try
            {
                StreamWriter SW = new StreamWriter(@path_to_input_file, false);
                using (SW)
                {
                    SW.Write(newlines);
                }
            }
            catch (OverflowException oe)
            {
                throw new OverflowException("Stack overflow, may be the file is too big?, " + oe.Message);
            }
            catch (IOException ioe)
            {
                throw new IOException("Error: the input file could not be read, " + ioe.Message);
            }
            Console.WriteLine("New data: \r\n{0}", newlines);
            Console.WriteLine("Data succesfully written to " + path_to_input_file);
        }
    }
}
